package com.springcloud.alibaba.consumer;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.springcloud.alibaba.service.PaymentServicee;
import com.springcloud.configclient.commons.entities.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class ConsumerController {
    @Value("${service-url.nacos-user-service}")
    private  String uri;
    @Autowired
    public RestTemplate restTemplate;
    //1、fallback+blockHandler测试
    @GetMapping(value = "/consumer/payment/{id}")
    @SentinelResource(value = "payment",fallback = "fallBack",blockHandler = "blockHandler")
    public CommonResult payment(@PathVariable("id") int id){
        System.out.println("---------consumer----------"+id);
        CommonResult forObject = restTemplate.getForObject(uri + "/payment/" + id, CommonResult.class, id);
        if (id == 4) {
            int n=10/0;
        }else if (forObject.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return forObject;
    }




    @Autowired
    private PaymentServicee paymentServicee;
    //1、fallback+blockHandler测试
    @GetMapping(value = "/consumer/payment1/{id}")
    @SentinelResource(value = "payment",fallback = "fallBack",blockHandler = "blockHandler")
    public CommonResult payment1(@PathVariable("id") int id) {
        return paymentServicee.payment(id);
    }
    public CommonResult fallBack(@PathVariable("id") int id,Throwable e){
        return new CommonResult(444,"fallback错误",e.getMessage());

    }
    public CommonResult blockHandler(@PathVariable("id") int id, BlockException e){
        return new CommonResult(444,"blockHandler错误",e.getMessage());
    }

    @GetMapping(value = "/consumer/zzz")
    @SentinelResource(value = "payment",fallback = "fallBack",blockHandler = "blockHandler")
    public CommonResult zzz() {
        int id=1;
        return paymentServicee.payment(id);
    }





}
